package com.dcivision.framework;

import java.sql.Connection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.bean.ProtectedObject;
import com.dcivision.framework.dao.ProtectedObjectDAObject;
import com.dcivision.framework.dao.ProtectedResourceDAObject;


public class ProtectedSourceManager {
  protected SessionContainer sessionContainer;
  protected Connection dbConn;
  
  private static final Log log = LogFactory.getLog(ProtectedSourceManager.class);
  
  public  ProtectedSourceManager(SessionContainer sessionContainer, Connection dbConn){
    this.sessionContainer = sessionContainer;
    this.dbConn = dbConn;
  }
 
  /* (non-Javadoc)
   * @see com.dcivision.framework.web.ProtectedFilterHelper#getProtection()
   */
  public String getProtection(Integer sourceID, Integer objectValue) {
    ProtectedObjectDAObject protectedObjectDAO = new ProtectedObjectDAObject(this.sessionContainer, this.dbConn);
    List objectList = null;
    try {
      if (!Utility.isEmpty(sourceID)) {
        objectList = protectedObjectDAO.getListBySourceID(sourceID);
        if (!Utility.isEmpty(objectList)) {
          if (objectList.size() <= 1) {
            ProtectedObject protectedObject = (ProtectedObject)objectList.get(0);
            return protectedObject.getProtection();
          } else if(!Utility.isEmpty(objectValue)) {
            // if have move one protectedobject and parameter objectValue is not null
            for (int i = 0; i < objectList.size(); i++) {
              ProtectedObject protectedObject = (ProtectedObject)objectList.get(i);
              if (objectValue.equals(protectedObject.getProtection())) {
                return protectedObject.getProtection();
              }
           }
          } 
        } 
      } else if (!Utility.isEmpty(objectValue)) {
        List protectedObjectList = protectedObjectDAO.getListByObjectValue(objectValue);
        if (!Utility.isEmpty(protectedObjectList)) {
          return ((ProtectedObject)protectedObjectList.get(0)).getProtection();
        }
      }
    } catch (ApplicationException ex) {
      log.error(ex, ex);
      return null;
    }
    return null;
  }
  
  public List getPropectedResource(String sourceUrl) throws ApplicationException{
    ProtectedResourceDAObject protectedResouceDAO = new ProtectedResourceDAObject(this.sessionContainer, this.dbConn);
    List resourceList = null;
    try {
      resourceList = protectedResouceDAO.getListByUrl(sourceUrl);
      if (!Utility.isEmpty(resourceList)) {
        return resourceList;
      } 
    } catch (ApplicationException ex) {
      log.error(ex, ex);
      return null;
    }
    return null;
  }

}
